package com.paradogs.framework.master.netty;

import com.paradogs.framework.core.events.ServerClientActiveEvent;
import com.paradogs.framework.core.events.ServerClientInactiveEvent;
import com.paradogs.framework.core.msg.ByteData;
import com.paradogs.framework.core.msg.MsgHeader;
import com.paradogs.framework.core.netty.PRConnHolder;
import com.paradogs.framework.core.netty.server.PRAbServerMsgHandler;
import com.paradogs.framework.core.netty.server.PRConnection;
import com.paradogs.framework.core.queue.PRQueueHolder;
import com.paradogs.framework.core.utils.EventUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * @author: yumi
 * @date: 2023/11/23  17:34
 * @Description: TODO
 */
@Slf4j
@Primary
@Component
@ChannelHandler.Sharable
public class MasterMsgHandler extends PRAbServerMsgHandler<ByteData> {

    @Override
    protected void processMsg(ByteData msg) throws Exception {
        PRQueueHolder.putMsg(PRQueueHolder.QueueType.MAIN, msg);
    }

    @Override
    protected void setProps(ChannelHandlerContext ctx, ByteData msg) {
        super.setProps(ctx, msg);
        MsgHeader header = msg.getMsgHeader();
        PRConnection conn = PRConnHolder.getConn(ctx.channel());
        if (conn != null) {
            header.setSendServer(conn.getType()); // 设置发送服标识
        }
    }

    /**
     * 连接建立事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        EventUtils.publishEvent(new ServerClientActiveEvent(ctx));
    }

    /**
     * 连接断开事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        PRConnection conn = PRConnHolder.removeConn(ctx.channel());

        EventUtils.publishEvent(new ServerClientInactiveEvent(ctx));
    }
}
